package com.sh.ssao.lottery.codeGenerator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;

import java.io.File;
import java.util.*;

class FastAutoGeneratorgo {

    final static String url = "jdbc:mysql://127.0.0.1:3306/choujiang?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false";
    final static String name = "root";
    final static String pwd = "1qaz@WSX3edc";
    final static String pkgpath = System.getProperty("user.dir")+"/src/main/";
    //模块名称
    final static String moduleName = "choujiang";
    //内路径
    final static String parentName="com.sh.ssao.lottery";

    /**
     * 数据源配置
     */
    private static final DataSourceConfig.Builder DATA_SOURCE_CONFIG = new DataSourceConfig
            .Builder(url, name, pwd);


    public static void main(String[] args) {


        FastAutoGenerator.create(DATA_SOURCE_CONFIG)
                // 全局配置
                .globalConfig( builder -> builder.author("gzgs")
                        .outputDir(pkgpath+"/java")
                        .commentDate("yyyy-MM-dd HH:mm:ss")
                        .dateType(DateType.ONLY_DATE)
                        .disableOpenDir()
                )

                // 包配置
                .packageConfig(builder-> builder.parent(parentName)
                        .moduleName(moduleName)
                        .entity("bean")
                        .service("service")
                        .serviceImpl("service.impl")
                        .mapper("mapper")
                        .controller("controller")
                        .pathInfo(new HashMap<OutputFile, String>(){{
                            put(OutputFile.xml,pkgpath+"/resources/mapper/"+moduleName);
                            put(OutputFile.other,pkgpath+"/resources");
                        }})
                )

                // 策略配置
                .strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名，多个英文逗号分隔？所有输入 all")))
                        .controllerBuilder().enableRestStyle().enableHyphenStyle()
                        .entityBuilder().enableLombok().addTableFills(
                                new Column("dms_create_time", FieldFill.INSERT),
                                new Column("dms_update_time", FieldFill.INSERT_UPDATE)
                        ).enableLombok()
                        .idType(IdType.NONE)
                        .build())
                /*
                    模板引擎配置，默认 Velocity 可选模板引擎 Beetl 或 Freemarker
                   .templateEngine(new BeetlTemplateEngine())
                   .templateEngine(new FreemarkerTemplateEngine())
                 */


                //模板配置
//                .templateConfig(builder -> builder
//                        .disable(TemplateType.XML)
//                )


                //自定义模板
                .injectionConfig(builder -> builder.beforeOutputFile(((tableInfo, stringObjectMap) -> {
                            System.out.println("tableInfo: " + tableInfo.getEntityName());
                        }))
                        .customFile(new HashMap<String,String>(){{
                    put("add.js","/templates/addjs.vm");//添加
                    put("edit.js","/templates/editjs.vm");//修改
                    put("list.js","/templates/listjs.vm");//列表
                    put("add.ftlh","/templates/addftlh.vm");//添加页面
                    put("edit.ftlh","/templates/editftlh.vm");//修改页面
                    put("list.ftlh","/templates/listftlh.vm");//列表页面
                }}).customMap(new HashMap<String,Object>(){{
                    put("addName","添加");
                    put("editName","修改");
                    put("listName","列表");
                    }})
                )
                //模板引擎重写
                .templateEngine(new VelocityTemplateEngine(){
                    @Override
                    protected void outputCustomFile(Map<String, String> customFile, TableInfo tableInfo, Map<String, Object> objectMap) {
                        String table_name = tableInfo.getName();
                        String otherPath = this.getPathInfo(OutputFile.other);
                        customFile.forEach((key, value) -> {
//                            System.out.println("---------"+key+":"+value);
                            String k = key.substring(key.lastIndexOf(".") + 1);
                            String fileUrl = otherPath;
                            if ("js".equals(k)) {
                                fileUrl += File.separator +"static"+File.separator+moduleName+File.separator+ table_name + File.separator + "%s";
                            }else if ("ftlh".equals(k)){
                                fileUrl += File.separator +"templates"+File.separator+moduleName+File.separator+ table_name + File.separator + "%s";
                            }
                            String fileName = String.format(fileUrl , key);
                            this.outputFile(new File(fileName), objectMap, value, this.getConfigBuilder().getInjectionConfig().isFileOverride());
                        });
                    }
                })
                .execute();



    }

    // 处理 all 情况
    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }
}
